import {
    ProFormUploadButtonProps,
    SearchTransformKeyFn
} from '@ant-design/pro-components';
import { getFileName, readImg } from './utils';
import { v4 } from 'uuid';
import { message, Upload } from 'antd';
import { uploadFileBySys } from './service';
export const convertValue = (value: any = '') => {
    if (!value) return [];
    if (typeof value === 'string') {
        const arr = value?.split(',');
        return arr.map((item: any) => {
            return {
                uid: v4(),
                name: getFileName(item),
                status: 'done',
                url: item,
                response: {
                    data: item,
                    url: item,
                },
            };
        });
    }
    return value || [];
};
export const uploadFormat: SearchTransformKeyFn = (value) => {
    if (!value.length) return '';
    if (typeof value === 'string') {
        return value;
    }
    return value?.map((item: any) => item?.response?.url || item?.response?.data || '').join(',');
};

export const proUploadConfig: ProFormUploadButtonProps = {
    transform: uploadFormat,
    convertValue,
};
type beforeUploadProps = {
    file: File;
    size?: {
        x: number;
        y: number;
    };
    maxSize?: number;
};

export const beforeUpload = async ({ size, file, maxSize }: beforeUploadProps) => {
    if (size && size.x && size.y) {
        const img: HTMLImageElement = await readImg(file);
        if (img.width !== size.x || img.height !== size.y) {
            message.error(`请上传分辨率为${size.x}px*${size.y}px的图片`);
            return Upload.LIST_IGNORE;
        }
        return file;
    }
    if (maxSize) {
        if (file.size < maxSize * 1048576) {
            return file;
        } else {
            message.error(`请上传小于${maxSize}M的文件`);
            Promise.reject(false);
            return Upload.LIST_IGNORE;
        }
    }
};
export const uploadProps = {
    customRequest: (options: any) => {
        const { file, onSuccess, onError, onProgress } = options;
        // file：文件对象 key：文件名 token：七牛云上传需要的token
        const option: ProgressTypes = {
            onUploadProgress: (event: ProgressEvent) => {
                // 上传进度发生变化时调用param.progress
                onProgress((event.loaded / event.total) * 100);
            },
        };
        uploadFileBySys({ file }, option)
            .then((res: any) => {
                if (Number(res.code) !== 200) {
                    onError(res.msg, {}, file);
                }
                onSuccess(res);
            })
            .catch((err: any) => {
                onError(err, {}, file);
            });
    },
};